package com.linkhub.oms.admin.config.i18n;

import com.linkhub.oms.common.constant.ProjectConstant;
import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.common.enums.LocaleTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Objects;

/**
 * @Description: 国际化语言解析
 * @Author: echo
 * @Date: 2024/3/3 14:58
 * @Version: 1.0
 */
public class I18nHeaderLocaleResolver implements LocaleResolver {


    /**
     * 从HttpServletRequest中获取Locale
     *
     * @param httpServletRequest httpServletRequest
     * @return 语言Local
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //如果没有就使用默认的
        Locale defaultLocale = Locale.US;
        //获取请求中的语言参数
        String language = httpServletRequest.getHeader(ProjectConstant.LOCALE_HEADER);
        if (StringUtils.isBlank(language)) {
            return defaultLocale;
        }
        //如果请求的链接中携带了 国际化的参数
        LocaleTypeEnum localeType = IEnumConvert.valueOf(language, LocaleTypeEnum.class);
        return Objects.isNull(localeType) ? defaultLocale : localeType.getLocale();

    }

    /**
     * 用于实现Locale的切换。比如SessionLocaleResolver获取Locale的方式是从session中读取，但如果
     * 用户想要切换其展示的样式(由英文切换为中文)，那么这里的setLocale()方法就提供了这样一种可能
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param locale   locale
     */
    @Override
    public void setLocale(@Nonnull HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }


}
